package com.ywl.exercise.controller.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ywl.exercise.entity.UserEntity;
import com.ywl.exercise.service.UserService;


@Controller
public class UserController {
	@Resource
	private UserService userServiceImpl;
	
	@RequestMapping(value = "/checkLoginId.do", method = RequestMethod.POST)
	public void checkLoginId(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		
		String loginid = request.getParameter("loginid");
		
		UserEntity entity = userServiceImpl.findUserByLoginId(loginid);
		boolean flag = false;
		if(entity != null) {
			flag = true;
		}
		
		out.println(flag);
		out.flush();
		out.close();
	}
	
	
	@RequestMapping(value = "/register.do", method = RequestMethod.POST)
	public void register(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		
		String loginid = request.getParameter("loginid");
		String nickname = request.getParameter("nickname");
		String password = request.getParameter("pwd");
		String birthday = request.getParameter("birthday");
		
		UserEntity entity = new UserEntity();
		entity.setLoginid(loginid);
		entity.setNickname(nickname);
		entity.setPassword(password);
		entity.setBirthday(Date.valueOf(birthday));
		userServiceImpl.saveUser(entity);
		
		//如果没有该session，则自动创建一个新的
		HttpSession session=request.getSession(true);
		session.setAttribute("user", entity);
		
		boolean flag = true;
		
		out.println(flag);
		out.flush();
		out.close();
	}
	
	@RequestMapping(value = "/login.do", method = RequestMethod.POST)
	public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		
		String loginid = request.getParameter("loginid");
		String password = request.getParameter("pwd");
		
		UserEntity entity = userServiceImpl.findUserByLoginId(loginid);
		String str = "不存在该用户,请检查用户名";
		if(entity != null) {
			if(password.equals(entity.getPassword())) {
				//如果没有该session，则自动创建一个新的
				HttpSession session=request.getSession(true);
				session.setAttribute("user", entity);
				str = "成功";
			}else {
				str = "密码错误,请检查密码";
			}
		}
		
		out.println(str);
		out.flush();
		out.close();
	}
}
